package com.advert.presentation.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;


public class IntegerConverter extends ConverterBase {

    protected Object convertToObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        Integer retVal = null;
        try {
            retVal = Integer.parseInt(s.replaceAll("\\W", ""));
        } catch (Exception e) {
            throw new ConverterException(buildConversionErrorMessage("INTEGER_FORMAT_INCORRECT"));
        }
        return retVal;
    }

    protected String convertToString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.##");
        decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(facesContext.getViewRoot().getLocale()));
        return decimalFormat.format(o);
    }

}
